import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'

import store from '../store/index'


const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'loagin',
    component: () => import('../views/Login.vue'),
    meta: { redirectAlreadyLogin: true }
  },
  {
    path: '/',
    name: 'home',
    component: () => import('../views/Home.vue'),
    meta: { requiresLogin: true },
    redirect: 'welcome',
    children: [
      {
        path: 'goods',
        component: () => import('../components/goods/HomeProductList.vue')
      },
      {
        path: 'welcome',
        component: () => import('../components/Welcome.vue')
      },
      {
        path: 'params',
        meta: { requiresLogin: true },
        component: () => import('@/components/goods/ProductParams/ProductParams.vue')
      },
      {
        path: 'categories',
        meta: { requiresLogin: true },
        component: () => import('@/components/goods/Categories/ProductCategories.vue')
      },
      {
        path: 'orders',
        meta: { requiresLogin: true },
        component: () => import('../components/orders/HomeOrders.vue')
      },
      {
        path: 'roles',
        meta: { requiresLogin: true },
        component: () => import('../components/rightsManagement/roles/HomeRightsToRoles.vue')
      },
      {
        path: 'rights',
        meta: { requiresLogin: true },
        component: () => import('../components/rightsManagement/rightsList/HomeRightsToList.vue')
      },
      {
        path: 'users',
        meta: { requiresLogin: true },
        component: () => import('../components/users/UsersList.vue')
      },
      {
        path: 'reports',
        component: () => import('../components/reports/Reports.vue')
      },
      {
        path: 'goods/edit',
        name: 'edit',
        meta: { requiresLogin: true },
        component: () => import('@/components/goods/ProductListRedact/ProductListRedact.vue')
      },
      {
        path: 'goods/add',
        name: 'add',
        meta: { requiresLogin: true },
        component: () => import('@/components/goods/ProductListAdd/ProductListAdd.vue')
      }
    ]
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const { state, token } = store.state.user
  const { redirectAlreadyLogin, requiresLogin } = to.meta
  if (!state) {
    if (token || localStorage.getItem('token')) {
      if (redirectAlreadyLogin) {
        next('/')
      } else {
        next()
      }
    } else {
      if (!requiresLogin) {
        next()
      } else {
        next('/login')
      }
    }
  } else {
    if (redirectAlreadyLogin) {
      next('/login')
    } else {
      next()
    }
  }
})

export default router
